<template>
  <div class="banner-management">
    <el-card>
      <div slot="header" class="card-header">
        <span class="card-title">轮播图管理</span>
        <el-button type="primary" @click="handleAdd" class="add-button">
          <i class="el-icon-plus"></i>
          添加轮播图
        </el-button>
      </div>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <el-row :gutter="20" class="search-row">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索轮播图标题或描述"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch"
              clearable
            />
          </el-col>
          <el-col :xs="12" :sm="6" :md="4" :lg="4" :xl="4">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 100%">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-col>
          <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
            <div class="search-buttons">
              <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
              <el-button @click="handleReset" size="small">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 轮播图列表 -->
      <el-table
        :data="bannerList"
        v-loading="loading"
        stripe
        style="width: 100%"
        :default-sort="{prop: 'sortOrder', order: 'ascending'}"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
        <el-table-column label="图片" width="120" align="center">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.imageUrl"
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              style="width: 80px; height: 50px; border-radius: 4px;"
              fit="cover"
            />
            <span v-else style="color: #999;">无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="linkUrl" label="跳转链接" min-width="150" show-overflow-tooltip />
        <el-table-column prop="sortOrder" label="排序" width="80" align="center" sortable />
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'" size="small">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template slot-scope="scope">
            <div class="action-buttons">
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)" plain>编辑</el-button>
              <el-button 
                size="mini" 
                :type="scope.row.status === 1 ? 'warning' : 'success'"
                @click="handleToggleStatus(scope.row)"
                plain
              >
                {{ scope.row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)" plain>删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </el-card>

    <!-- 添加/编辑轮播图对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        :model="bannerForm"
        :rules="bannerRules"
        ref="bannerForm"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="bannerForm.title" placeholder="请输入轮播图标题" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="bannerForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入轮播图描述"
          />
        </el-form-item>
        
        <el-form-item label="图片" prop="imageUrl">
          <div class="image-upload">
            <el-upload
              class="image-uploader"
              :action="uploadUrl"
              :headers="getUploadHeaders()"
              :show-file-list="false"
              :on-success="handleImageSuccess"
              :before-upload="beforeImageUpload"
              accept="image/*"
            >
              <img v-if="bannerForm.imageUrl" :src="bannerForm.imageUrl" class="uploaded-image" />
              <i v-else class="el-icon-plus image-uploader-icon"></i>
            </el-upload>
            <div class="upload-tip">只能上传jpg/png文件，且不超过5MB</div>
          </div>
        </el-form-item>
        
        <el-form-item label="跳转链接" prop="linkUrl">
          <el-input v-model="bannerForm.linkUrl" placeholder="请输入跳转链接（可选）" />
        </el-form-item>
        
        <el-form-item label="排序值" prop="sortOrder">
          <el-input-number v-model="bannerForm.sortOrder" :min="0" :max="999" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="bannerForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="bannerForm.startTime"
            type="date"
            placeholder="选择开始时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="bannerForm.endTime"
            type="date"
            placeholder="选择结束时间"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
      </div>
    </el-dialog>

    <!-- 查看轮播图详情对话框 -->
    <el-dialog
      title="轮播图详情"
      :visible.sync="viewDialogVisible"
      width="500px"
    >
      <div class="banner-detail">
        <div class="detail-item">
          <label>标题:</label>
          <p>{{ currentBanner.title }}</p>
        </div>
        <div class="detail-item">
          <label>描述:</label>
          <p>{{ currentBanner.description }}</p>
        </div>
        <div class="detail-item">
          <label>图片:</label>
          <el-image
            v-if="currentBanner.imageUrl"
            :src="currentBanner.imageUrl"
            :preview-src-list="[currentBanner.imageUrl]"
            style="width: 200px; height: 120px; border-radius: 4px;"
            fit="cover"
          />
          <span v-else>无图片</span>
        </div>
        <div class="detail-item">
          <label>跳转链接:</label>
          <p>{{ currentBanner.linkUrl || '无' }}</p>
        </div>
        <div class="detail-item">
          <label>排序值:</label>
          <p>{{ currentBanner.sortOrder }}</p>
        </div>
        <div class="detail-item">
          <label>状态:</label>
          <el-tag :type="currentBanner.status === 1 ? 'success' : 'danger'">
            {{ currentBanner.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </div>
        <div class="detail-item">
          <label>开始时间:</label>
          <p>{{ currentBanner.startTime || '无' }}</p>
        </div>
        <div class="detail-item">
          <label>结束时间:</label>
          <p>{{ currentBanner.endTime || '无' }}</p>
        </div>
        <div class="detail-item">
          <label>创建时间:</label>
          <p>{{ formatDate(currentBanner.createdAt) }}</p>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "BannerManagement",
  data() {
    return {
      loading: false,
      submitting: false,
      bannerList: [],
      searchForm: {
        keyword: "",
        status: null
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      dialogVisible: false,
      viewDialogVisible: false,
      dialogTitle: "添加轮播图",
      currentBanner: {},
      bannerForm: {
        id: null,
        title: "",
        description: "",
        imageUrl: "",
        linkUrl: "",
        sortOrder: 0,
        status: 1,
        startTime: "",
        endTime: ""
      },
      bannerRules: {
        title: [
          { required: true, message: "请输入轮播图标题", trigger: "blur" }
        ],
        imageUrl: [
          { required: true, message: "请上传轮播图图片", trigger: "change" }
        ]
      },
      uploadUrl:  "http://localhost:3333/api/admin/banners/upload"
    }
  },

  mounted() {
    this.loadBannerList()
  },

  methods: {
    async loadBannerList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          keyword: this.searchForm.keyword,
          status: this.searchForm.status
        }
        
        const response = await this.$http.get("/admin/banners", { params })
        if (response.data.code === 200) {
          this.bannerList = response.data.data.records || []
          this.pagination.total = response.data.data.total || 0
        } else {
          this.$message.error(response.data.message || "获取轮播图列表失败")
        }
      } catch (error) {
        console.error("获取轮播图列表失败:", error)
        this.$message.error("获取轮播图列表失败")
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.pagination.currentPage = 1
      this.loadBannerList()
    },

    handleReset() {
      this.searchForm = {
        keyword: "",
        status: null
      }
      this.pagination.currentPage = 1
      this.loadBannerList()
    },

    handleAdd() {
      this.dialogTitle = "添加轮播图"
      this.bannerForm = {
        id: null,
        title: "",
        description: "",
        imageUrl: "",
        linkUrl: "",
        sortOrder: 0,
        status: 1,
        startTime: "",
        endTime: ""
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = "编辑轮播图"
      this.bannerForm = {
        id: row.id,
        title: row.title,
        description: row.description,
        imageUrl: row.imageUrl,
        linkUrl: row.linkUrl,
        sortOrder: row.sortOrder,
        status: row.status,
        startTime: row.startTime,
        endTime: row.endTime
      }
      this.dialogVisible = true
    },

    handleView(row) {
      this.currentBanner = { ...row }
      this.viewDialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm("确定要删除这个轮播图吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        
        const response = await this.$http.delete(`/admin/banners/${row.id}`)
        if (response.data.code === 200) {
          this.$message.success("删除成功")
          this.loadBannerList()
        } else {
          this.$message.error(response.data.message || "删除失败")
        }
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除轮播图失败:", error)
          this.$message.error("删除失败")
        }
      }
    },

    async handleToggleStatus(row) {
      try {
        const newStatus = row.status === 1 ? 0 : 1
        const response = await this.$http.put(`/admin/banners/${row.id}/status`, {
          status: newStatus
        })
        
        if (response.data.code === 200) {
          this.$message.success(response.data.message || "操作成功")
          this.loadBannerList()
        } else {
          this.$message.error(response.data.message || "操作失败")
        }
      } catch (error) {
        console.error("切换轮播图状态失败:", error)
        this.$message.error("操作失败")
      }
    },

    handleSubmit() {
      this.$refs.bannerForm.validate(async (valid) => {
        if (valid) {
          this.submitting = true
          try {
            const formData = new FormData()
            Object.keys(this.bannerForm).forEach(key => {
              if (this.bannerForm[key] !== null && this.bannerForm[key] !== undefined) {
                formData.append(key, this.bannerForm[key])
              }
            })
            
            let response
            if (this.bannerForm.id) {
              response = await this.$http.put(`/admin/banners/${this.bannerForm.id}`, formData, {
                headers: { "Content-Type": "multipart/form-data" }
              })
            } else {
              response = await this.$http.post("/admin/banners", formData, {
                headers: { "Content-Type": "multipart/form-data" }
              })
            }
            
            if (response.data.code === 200) {
              this.$message.success(response.data.message || "操作成功")
              this.dialogVisible = false
              this.loadBannerList()
            } else {
              this.$message.error(response.data.message || "操作失败")
            }
          } catch (error) {
            console.error("提交轮播图失败:", error)
            this.$message.error("操作失败")
          } finally {
            this.submitting = false
          }
        }
      })
    },

    handleDialogClose() {
      this.$refs.bannerForm.resetFields()
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.loadBannerList()
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadBannerList()
    },

    handleImageSuccess(response) {
      if (response.code === 200) {
        this.bannerForm.imageUrl = response.data.imageUrl
        this.$message.success("图片上传成功")
      } else {
        this.$message.error(response.message || "图片上传失败")
      }
    },

    beforeImageUpload(file) {
      const isImage = file.type.startsWith("image/")

      if (!isImage) {
        this.$message.error("只能上传图片文件!")
        return false
      }

      return true
    },

    formatDate(date) {
      if (!date) return "未知"
      return new Date(date).toLocaleString("zh-CN")
    },

    getUploadHeaders() {
      const token = localStorage.getItem("token")
      return {
        Authorization: token ? `Bearer ${token}` : ""
      }
    }
  }
}
</script>

<style scoped>
.banner-management {
  padding: 0;
  width: 100%;
  min-height: calc(100vh - 120px);
}

/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.add-button {
  margin-left: auto;
}

.search-area {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.search-row {
  display: flex;
  align-items: center;
}

.search-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
  padding: 0 10px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
  justify-content: center;
}

.action-buttons .el-button {
  margin: 0;
  padding: 5px 8px;
  font-size: 12px;
}

/* 图片上传样式 */
.image-upload {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 100px;
}

.image-uploader:hover {
  border-color: #409EFF;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.uploaded-image {
  width: 178px;
  height: 100px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

/* 详情样式 */
.banner-detail {
  padding: 20px 0;
}

.detail-item {
  margin-bottom: 15px;
}

.detail-item label {
  font-weight: bold;
  color: #606266;
  margin-right: 10px;
}

.detail-item p {
  margin: 5px 0;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .action-buttons {
    flex-direction: column;
    gap: 2px;
  }
  
  .action-buttons .el-button {
    width: 100%;
    margin: 1px 0;
  }
}

@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .add-button {
    margin-left: 0;
    width: 100%;
  }
  
  .search-area {
    padding: 15px;
  }
  
  .search-row {
    flex-direction: column;
    gap: 15px;
  }
  
  .search-buttons {
    justify-content: center;
    width: 100%;
  }
  
  .pagination-area {
    text-align: center;
  }
  
  .action-buttons {
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .action-buttons .el-button {
    flex: 1;
    min-width: 60px;
  }
}

@media (max-width: 480px) {
  .banner-management {
    padding: 0 5px;
  }
  
  .search-area {
    padding: 10px;
    margin-bottom: 15px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
    margin: 2px 0;
  }
}
</style>
